<template>
  <el-dialog
    style="border-radius: 0 !important; padding: 0 !important"
    v-model="open"
    :fullscreen="true"
    :show-close="false"
    class="contract-dialog"
    custom-class="contract-dialog"
    @close="close"
  >
    <!-- Dialog Header -->
    <template #header>
      <div class="dialog-header">
        <div class="header-left">
          <el-icon class="back-btn" @click="close"><Back size="28px" /></el-icon>

          <span class="title">{{ title }}</span>
        </div>
        <div class="header-right">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </div>
    </template>

    <!-- Dialog Content -->
    <div class="dialog-content">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="contract-form" label-position="top">
        <!-- Basic Information -->
        <div class="form-section">
          <div class="section-title">
            <div class="title-marker"></div>
            基本信息
          </div>
          <div>
            <div class="form-grid">
              <el-form-item label="合同类型" prop="contractTypeId">
                <el-select v-model="form.contractTypeId" placeholder="请选择" clearable>
                  <el-option v-for="(item, index) in contractTypeList" :key="index" :label="item.contractTypeName" :value="item.id"></el-option>
                  <template #footer>
                  <div >
                    <el-button style="width: 120px;margin:0 auto" plain color="#626aef" :dark="false" size="small" @click="addClueSource(1)" :icon="Plus">
                    <el-icon color="fff"><Plus /></el-icon>添加
                  </el-button>
                  </div>
                </template>
                </el-select>
              </el-form-item>
              <el-form-item label="合同编号">
                <el-input v-model="form.contractNumber" placeholder="系统自动生成编号：SO202401010001" disabled></el-input>
              </el-form-item>
              <el-form-item label="合同名称" prop="contractName">
                <el-input v-model="form.contractName" placeholder="请输入"></el-input>
              </el-form-item>
              <el-form-item label="签订日期" prop="signDate">
                <el-date-picker
                  v-model="form.signDate"
                  type="date"
                  value-format="YYYY-MM-DD hh:mm:ss"
                  placeholder="请选择"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>

              <el-form-item label="跟单来源" prop="clueSourceId">
                <el-select :disabled="isLink" v-model="form.clueSourceId" clearable reserve-keyword placeholder="请选择跟单来源">
                  <el-option v-for="item in clueSource" :key="item.id" :label="item.sourceName" :value="item.id" />
                </el-select>
              </el-form-item>

              <el-form-item  label="关联客户" prop="supplierId" @click="showCustomer">
                <el-input :disabled="isLink" v-model="form.supplierName" placeholder="请选择客户" size="normal" clearable suffix-icon="search"></el-input>
              </el-form-item>

              <el-form-item label="关联商机" @click="showClue" prop="clueNumber">
                <el-input :disabled="isLink" v-model="form.clueNumber" placeholder="请关联跟单" size="normal" clearable suffix-icon="search"></el-input>
              </el-form-item>
              <el-form-item label="合同开始日期" prop="beginDate">
                <el-date-picker
                  v-model="form.beginDate"
                  type="date"
                  value-format="YYYY-MM-DD hh:mm:ss"
                  placeholder="请选择"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>

              <el-form-item label="合同结束日期" prop="endDate">
                <el-date-picker
                  v-model="form.endDate"
                  type="date"
                  value-format="YYYY-MM-DD hh:mm:ss"
                  placeholder="请选择"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>

              <el-form-item label="签订人" prop="signUserId">
                <el-select :disabled="isLink" v-model="form.signUserId" clearable reserve-keyword placeholder="请选择签订人">
                  <el-option v-for="item in assistList" :key="item.userId" :label="item.realityName" :value="item.userId">
                    <span style="float: left">{{ item.realityName }}</span>
                    <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
                      {{ item.userName }}
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="协同人" prop="coordinationUserId">
                <el-select  v-model="coordinationUserIds" multiple clearable reserve-keyword placeholder="请选择协同人">
                  <el-option v-for="item in assistList" :key="item.userId" :label="item.realityName" :value="item.userId">
                    <span style="float: left">{{ item.realityName }}</span>
                    <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
                      {{ item.userName }}
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="开票方式" prop="invoicingMethodId">
                <el-select v-model="form.invoicingMethodId" placeholder="请选择" clearable>
                  <el-option v-for="(item, index) in invoicingMethodList" :key="index" :label="item.methodName" :value="item.id"></el-option>
                  <template #footer>
                  <div >
                    <el-button style="width: 120px;margin:0 auto" plain color="#626aef" :dark="false" size="small" @click="addClueSource(2)" :icon="Plus">
                    <el-icon color="fff"><Plus /></el-icon>添加
                  </el-button>
                  </div>
                </template>
                </el-select>
              </el-form-item>
              <el-form-item label="付款方式" prop="paymentMethod">
                <el-input v-model="form.paymentMethod" size="normal" clearable placeholder="请输入付款方式"></el-input>
              </el-form-item>

              <el-form-item label="所属区域" prop="collaborator">
                <el-select disabled v-model="form.saleArea" value-key="" placeholder="客户自带销售区域" clearable filterable>
                  <el-option v-for="item in areaList" :key="item.id" :label="item.areaName" :value="item.id + ''"> </el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="签订日期" prop="signDate" required>
                <el-date-picker v-model="form.signDate" type="date" placeholder="请选择" style="width: 100%"></el-date-picker>
              </el-form-item> -->
            </div>
          </div>
        </div>

        <!-- Sales Information -->
        <div class="form-section">
          <div class="products-table">
            <div class="table-header">
              
            <div style="display: flex;align-items: center;"><div class="title-marker"></div>
              <span>关联产品</span></div>
              <div class="table-actions">
                <el-button type="primary" @click="handleAdd"
                  ><el-icon><Plus color="#fff" /></el-icon>批量添加</el-button
                >
              </div>
            </div>
            <el-table v-loading="loading" :data="dataSource" style="width: 100%" scrollbar-always-on>
              <el-table-column type="index" label="序号" width="50"></el-table-column>
              <el-table-column label="商品图片" align="center" min-width="120">
                <template #default="scope">
                  <ImagePreview :width="100" :height="100" :src="scope.row.goodsPackImg" :preview-src-list="[scope.row.goodsPackImg]" />
                </template>
              </el-table-column>
              <el-table-column label="商品名称" align="left" prop="goodsName" min-width="200" />
              <el-table-column label="商品品牌" align="center" prop="brandName" />
              <el-table-column label="商品数量" align="left" prop="goodsNumber" width="180">
                <template #default="scope">
                  <el-input
                    @change="quantityChange($event, scope.row, scope.$index)"
                    v-model="scope.row.goodsNumber"
                    placeholder="请输入商品数量"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="商品价格" align="left" prop="goodsPrice" width="180">
                <template #default="scope">
                  <el-input
                    style="width: 150px"
                    @change="quantityChange($event, scope.row, scope.$index)"
                    v-model="scope.row.goodsPrice"
                    placeholder="请输入商品价格"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="金额" align="center" prop="goodsAmount" />
              <el-table-column label="计价方式">
                <template #default="scope">
                  {{ selectDictLabel(goods_price_type, scope.row.goodsPriceTypeDictValue) }}
                </template>
              </el-table-column>
              <el-table-column label="开始日期" align="center" prop="beginDate" min-width="180">
                <template #default="scope">
                  <el-date-picker
                    v-model="scope.row.beginDate"
                    type="date"
                    style="width: 100%"
                    :picker-ptions="pickerOptionsStart"
                    value-format="YYYY-MM-DD hh:mm:ss"
                    @change="handlePeriodicNumChange(scope.row)"
                    :disabled="disabled"
                  ></el-date-picker>
                </template>
              </el-table-column>

              <el-table-column label="周期" align="center" prop="periodicNum" width="120">
                <template #default="scope">
                  <el-input v-model.number="scope.row.periodicNum" @change="handlePeriodicNumChange(scope.row)" :disabled="disabled"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="到期日期" align="center" prop="endDate" min-width="180">
                <template #default="scope">
                  <el-date-picker
                    v-model="scope.row.endDate"
                    type="date"
                    style="width: 100%"
                    :picker-ptions="pickerOptionsEnd"
                    value-format="YYYY-MM-DD hh:mm:ss"
                    @change="handleEndDateChange(scope.row)"
                    :disabled="disabled"
                  ></el-date-picker>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注"></el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button type="text" size="small" @click="handleDeleteProduct(scope.$index)"> 删除 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="form-section">
          <el-form-item label="附件">
            <el-upload
              drag
              style="width: 400px"
              :headers="headers"
              v-model:file-list="fileList"
              :on-success="(res, file) => handleUploadSuccess(res, file)"
              :action="uploadUrl"
              multiple
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">拖拽或 <em>点击上传</em></div>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
      <custom-dialog ref="customDialog" @ok="customerOk"></custom-dialog>
      <select-material-form ref="selectMaterialForm" @ok="selectOk"></select-material-form>
      <select-clue-form ref="selectClueForm" @ok="clueOk"></select-clue-form>
      <clueSourceAddForm ref="clueSourceAddForm" @ok="clueSourceOk"></clueSourceAddForm>
    </div>
  </el-dialog>
</template>
  
  <script>
  import customDialog from '@/views/goods/customer/modules/custom-dialog.vue';
import modelMixin from '@/mixins/modelMixin';
import selectMaterialForm from '@/views/goods/quote/modules/selectMaterialForm';
import selectClueForm from '@/views/goods/clue/modules/clue-dialog.vue';
import { formatDate } from '@/utils/index';
import { globalHeaders } from '@/utils/request';
import contract from '@/api/goods/contract';
import { getSupplier } from '@/api/goods/supplier/index';
import clueSourceAddForm from '@/views/goods/clueSource/modules/addForm.vue'
import moment from 'moment';
export default {
  name: 'ContractDialog',
  components: {
    customDialog,
    selectMaterialForm,
    selectClueForm,
    clueSourceAddForm
  },
  mixins: [modelMixin],
  data() {
    return {
      open: false,
      isLink:false,
      funcObj: contract,
      uploadUrl: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload', // 上传的图片服务器地址
      title: '',
      headers: globalHeaders(),
      fileList: [],
      dataSource: [],
      goods_price_type: [],
      fileUrls: [],
      coordinationUserIds:[],
      form: {
        contractNumber: '',
        contractTypeId: '',
        contractName: '',
        clueSourceId: '',
        supplierId: '',
        beginDate: '',
        endDate: '',
        signUserId: '',
        invoicingMethodId: '',
        signDate: moment().format('YYYY-MM-DD hh:mm:ss'),
        startDate: '',
        endDate: '',
        owner: '',
        paymentMethod: '',
        remark: '',
        jzgContractDetailVoList: [],
        annex: '',
        saleAreaName: '',
        contractTypeDictValue: '',
        clueSourceDictValue: '',
        invoicingMethodDictValue: '',
        signUserDictValue: '',
        ownerDictValue: '',
      },
      rules: {
        contractTypeId: [{ required: true, message: '请选择合同类型', trigger: 'blur' }],
        contractName: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
        clueSourceId: [{ required: true, message: '请选择跟单来源', trigger: 'blur' }],
        supplierId: [{ required: true, message: '请选择关联客户', trigger: 'change' }],
        beginDate: [{ required: true, message: '请选择关合同开始时间', trigger: 'change' }],
        endDate: [{ required: true, message: '请选择关合同结束时间', trigger: 'change' }],
        supplierId: [{ required: true, message: '请选择关联客户', trigger: 'change' }],
        signUserId: [{ required: true, message: '请选择公司签订人', trigger: 'change' }],
        invoicingMethodId: [{ required: true, message: '请选择公开票方式', trigger: 'change' }],
        signDate: [{ required: true, message: '请选择签订日期', trigger: 'change' }],
        startDate: [{ required: true, message: '请选择合同开始日期', trigger: 'change' }],
        endDate: [{ required: true, message: '请选择合同结束日期', trigger: 'change' }],
        signDate: [{ required: true, message: '请选择合同签订日期', trigger: 'change' }],
        owner: [{ required: true, message: '请选择负责人', trigger: 'change' }],
        paymentMethod: [{ required: true, message: '请输入付款方式', trigger: 'change' }]
      }
    };
  },
  created() {
    this.getArea();
    this.listInvoicingMethod();
    this.listContractType();
    this.getClueSourceAllList();
    this.getUserNotPermission();
    this.getDicts('goods_price_type');
  },
  methods: {
    add() {
      this.open = true;
      this.isLink = false;
      this.title = '新增合同';
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
      this.getContractNumber();
    },
    edit(row) {
      this.title = '编辑合同';
      this.open = true;
      this.isLink = false;
      this.getDetail(row);
      getSupplier(row.supplierId).then((res) => {
        this.form.saleAreaName = res.data.saleAreaName;
      });
    },
    link(info) {
      console.log('info',info);
      this.open = true;
      this.isLink = true
      this.title = '新增合同';
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
      
      this.form = {
        supplierId: info.supplierId,
        supplierName: '',
        saleArea: info.country,
        contractName: '',
        clueSourceId: info.clueSource,
        clueId: info.id || info.clueId,
        clueNumber: info.clueNumber,
        coordinationUserId: info.assistUserId,
        signUserId: info.followUserId,

        beginDate: '',
        endDate: '',
        invoicingMethodId: '',
        signDate: moment().format('YYYY-MM-DD hh:mm:ss'),
        startDate: '',
        endDate: '',
        owner: '',
        paymentMethod: '',
        remark: '',
        jzgContractDetailVoList: []
      },
      
      this.coordinationUserIds = info.coordinationUserId ? info.coordinationUserId.split(',') : [];

      getSupplier(info.supplierId).then((res) => {
        console.log(999999,res);
        this.form.saleAreaName = res.data.saleAreaName;
        this.form.supplierName = res.data.supplierName;
      });
      this.dataSource = (info.jzgClueMaterialList || info.jzgClueMaterialVoList).map((v) => {
        return {
          goodsId: v.goodsId,

          goodsPrice: v.price,
          goodsAmount: v.quantity * v.price,
          comment: v.remark,
          goodsNumber: +v.quantity,
          goodsPriceTypeDictValue: v.goodsPriceTypeDictValue,
          brandName: v.brandName,
          goodsPackImg: v.packImg
        };
      });
      this.getContractNumber();
    },
    detailAfter() {
      this.dataSource = this.form.jzgContractDetailVoList;
      // 组装附件
      this.fileList = (this.form.annex || '').split(',').map((v) => ({
        name: v,
        url: v,
        status: 'success'
      }));
      this.coordinationUserIds = []
      this.coordinationUserIds = this.form.coordinationUserId ? this.form.coordinationUserId.split(',').map(v => v) : [];
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    close() {
      this.open = false;
      this.form = {};
      this.dataSource = [];
      this.fileList = [];
    },
    handleAdd() {
      this.$refs.selectMaterialForm.show();
    },
    // 删除关联产品
    handleDeleteProduct(index) {
      this.$modal.confirm('你确定要删除该条数据吗?').then(() => {
        this.dataSource.splice(index, 1);
      });
    },
    quantityChange(value, row, index) {
      if (row.goodsPrice && row.goodsNumber) {
        row.goodsAmount = row.goodsPrice * row.goodsNumber;
        this.dataSource.splice(index, 1, row);
      }
    },
    selectOk(data) {
      this.dataSource = data.map((v) => {
        let data = {
          ...v,
          goodsId: v.id,
          goodsPrice: v.retailPrice,
          goodsAmount: v.goodsAmount,
          comment: v.remark,
          goodsNumber: v.goodsNumber,
          goodsPriceTypeDictValue: v.goodsPriceTypeDictValue,
          brandName: v.brandName,
          goodsPackImg: v.packImg
        };
        delete data.id;
        return data;
      });
    },
    showCustomer() {
      this.$refs.customDialog.open();
    },
    showClue() {
      this.$refs.selectClueForm.open();
    },
    clueOk(rows) {
      let clue = rows[0];

      this.form.clueNumber = clue.clueName;
      this.form.clueId = clue.id;
    },
    clueSourceOk(){
      if(this.currentType == 1){
        this.listContractType();
      }else{
        this.listInvoicingMethod();
      }
    },
    customerOk(rows) {
      let customer = rows[0];
      this.form.supplierId = customer.id;
      this.form.supplierName = customer.supplierName;
      this.form.saleArea = customer.saleArea;
    },

    handlePeriodicNumChange(row) {
      if (row.beginDate && row.periodicNum > 0) {
        let date = row.beginDate;
        date = Date.parse(new Date(date)) / 1000; // 转换成时间戳，返回值是ms，除1000后转化成秒
        date += 86400 * row.periodicNum; // 一天是86400秒
        let newDate = new Date(parseInt(date) * 1000); // 把时间戳转换成日期
        //这步就是给所需变化的值赋值
        row.endDate = formatDate(newDate);
      }
    },
    handleEndDateChange(row) {
      if (row.beginDate && row.endDate) {
        let date1 = Date.parse(new Date(row.beginDate));
        let date2 = Date.parse(new Date(row.endDate));
        row.periodicNum = parseInt(Math.abs(date2 - date1) / 1000 / 86400);
      }
    },

    // 上传成功
    handleUploadSuccess(res, file, key) {
      // 如果上传成功
      if (res.code == 200) {
        this.fileUrls.push(res.data.url);
      } else {
        this.$modal.msgError(res.msg);
      }
      console.log(this.fileList, '123');
    },

    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit('submit', this.form);
          this.close();
        }
      });
    },
    addClueSource(type){
      this.currentType = type;
      this.$refs.clueSourceAddForm.add({}, type);
    },
    validateForm() {
      if (!this.dataSource.length) {
        this.$modal.msgError('请选择关联产品！');
        return false;
      }
      for (let index = 0; index < this.dataSource.length; index++) {
        const el = this.dataSource[index];
        if (!el.goodsNumber) {
          this.$modal.msgError(`请输入第${index + 1}行产品数量！`);
          return false;
        }
        if (!el.goodsPrice) {
          this.$modal.msgError(`请输入第${index + 1}行产品单价！`);
          return false;
        }
        if (!el.beginDate) {
          this.$modal.msgError(`请输入第${index + 1}行产品开始日期！`);
          return false;
        }
        if (!el.endDate) {
          this.$modal.msgError(`请输入第${index + 1}行产品结束日期！`);
          return false;
        }
      }
      return true;
    },
    // 组装待提交的数据
    classifyForm() {
      if (!this.validateForm()) {
        throw new Error('表单验证失败');
      }
      this.form.annex = this.fileList
        .map((v) => {
          if (v.response) {
            return v.response.data.url;
          } else {
            return v.url;
          }
        })
        .join(',');
      this.form.jzgContractDetailVoList = this.dataSource;
      
      this.form.coordinationUserId = this.coordinationUserIds.join(',');
    },
    getContractNumber() {
      contract.getContractNumber().then((res) => {
        this.form.contractNumber = res.data;
      });
    }
  }
};
</script>
  
  <style scoped lang="scss">
.contract-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
}

.contract-dialog .el-dialog__header {
  display: none;
}

.contract-dialog .el-dialog__body {
  flex: 1;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 32px;
}
.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}
.header-left .el-button {
  font-size: 16px;
  font-weight: 500;
}

.header-right {
  display: flex;
  gap: 12px;
}

.dialog-content {
  flex: 1;
  padding: 24px;
  background-color: #f5f7fa;
  overflow-y: hidden;
}
.contract-form {
  width: 960px;
  margin: 0 auto;
}
.back-btn {
  font-size: 28px;
}
.back-btn:hover {
  color: #2468f2;
  cursor: pointer;
}
.form-section {
  background: #fff;
  border-radius: 4px;
  padding: 24px;
  margin-bottom: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 24px;
}
.title {
  font-size: 14px;
}

.title-marker {
  width: 2px;
  height: 14px;
  background: #2468f2;
  margin-right: 8px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
}

.products-table {
  margin-top: 16px;
}
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.empty-products {
  padding: 32px;
  text-align: center;
  color: #909399;
}

.empty-icon {
  width: 64px;
  height: 64px;
  margin-bottom: 8px;
}

/* Element UI Overrides */
.el-form-item__label {
  font-weight: normal;
  color: #606266;
}

.el-input__inner,
.el-select .el-input__inner {
  height: 32px;
  line-height: 32px;
}

.el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label:before,
.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
  color: #2468f2;
}

.el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 500;
}

.el-button--primary {
  background-color: #2468f2;
  border-color: #2468f2;
}

.el-button--primary:hover,
.el-button--primary:focus {
  background-color: #1d54cc;
  border-color: #1d54cc;
}
</style>
<style lang="scss">
.el-overlay .el-overlay-dialog .contract-dialog .el-dialog__body {
  padding: 0 !important;
}
.contract-dialog .el-dialog__body {
  max-height: calc(100vh - 57px) !important;
}
</style>